package com.marketlive.system.trace.log;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/*
(C) Copyright MarketLive. 2006. All rights reserved.
MarketLive is a trademark of MarketLive, Inc.
Warning: This computer program is protected by copyright law and international treaties.
Unauthorized reproduction or distribution of this program, or any portion of it, may result
in severe civil and criminal penalties, and will be prosecuted to the maximum extent
possible under the law.
*/

import org.apache.log4j.WriterAppender;
import org.marketlive.system.trace.ITraceSession;

import java.io.StringWriter;

/**
 * Implementation of Log4J appender that writes to a buffer.  The buffer is then
 * output to the jsp page.
 */
public class LogTraceAppender extends WriterAppender {

    public static final String TRACE_BUFFER_KEY = "trace.log.appender";

    /**
     * Logger
     */
    private static Log log = LogFactory.getLog(LogTraceAppender.class);

    private static ThreadLocalBufferWriter threadLocalWriter;

    public LogTraceAppender() {
        threadLocalWriter = new ThreadLocalBufferWriter();
        setWriter(threadLocalWriter);
    }


    /**
     * Binds the current thread to the current request so logging calls are written
     * to the buffer.
     */
    public void bindRequest(ITraceSession traceSession) {
        threadLocalWriter.startRecording(getWriter(traceSession));

    }

    /**
     * Unbinds the request from the thread.  Logging calls are no longer written to the
     * buffer.
     */
    public void unbindRequest(ITraceSession traceSession) {
        threadLocalWriter.stopRecording();
    }

    public String getBufferString() {
        return threadLocalWriter.getBufferString();
    }

    public void clearBuffer() {
        // do nothing
    }

    protected StringWriter getWriter(ITraceSession traceSession) {
        StringWriter writer = (StringWriter) traceSession.getAttribute(TRACE_BUFFER_KEY);
        if (writer == null) {
            writer = new StringWriter();
            log.debug("Stored writer in traceSession:" + writer);
            traceSession.setAttribute(TRACE_BUFFER_KEY, writer);
        }
        return writer;
    }

    protected void resetWriter(ITraceSession traceSession) {
        StringWriter writer = new StringWriter();
        traceSession.setAttribute(TRACE_BUFFER_KEY, writer);
    }
}
